﻿using Basic.FormModel.DB;
using Basic.FormModel.PhyQuery;
using Basic.FormRemoteModel;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Basic.FormDAL.Repository
{
    internal class PhysicalQueryDAL : BasicDAL<DBPhysicalQueryLayout, long>, IPhysicalQueryDAL
    {
        public PhysicalQueryDAL ( IRepository<DBPhysicalQueryLayout> basicDAL ) : base(basicDAL, "physical.query")
        {
        }
        public long Add ( PhyQueryAdd data )
        {
            DBPhysicalQueryLayout add = data.ConvertMap<PhyQueryAdd, DBPhysicalQueryLayout>();
            add.Id = IdentityHelper.CreateId();
            add.Sort = this._BasicDAL.Max(c => c.FormId == data.FormId && c.Location == data.Location, c => c.Sort) + 1;
            this._BasicDAL.Insert(add);
            return add.Id;
        }
        public PhyQuerySort[] GetSorts ( long formId, LayoutLocation location )
        {
            return this._BasicDAL.Gets<PhyQuerySort>(a => a.FormId == formId && a.Location == location);
        }
        public void SetSort ( KeyValuePair<long, int>[] sort )
        {
            ISqlQueue<DBPhysicalQueryLayout> queue = this._BasicDAL.BeginQueue();
            sort.ForEach(c =>
            {
                queue.UpdateOneColumn(a => a.Sort == c.Value, a => a.Id == c.Key);
            });
            _ = queue.Submit();
        }
        public void SetSort ( long id, int sort )
        {
            if ( !this._BasicDAL.Update(a => a.Sort == sort, a => a.Id == id) )
            {
                throw new ErrorException("form.physical.query.set.fail");
            }
        }
        public int GetMaxSort ( long formId, LayoutLocation location )
        {
            return this._BasicDAL.Max(a => a.FormId == formId && a.Location == location, a => a.Sort);
        }
    }
}
